class Nutrition {
  final String name;
  final String type;
  final dynamic rl; // 热量
  final dynamic dbz; // 蛋白质
  final dynamic zf; // 脂肪
  final dynamic shhf; // 碳水化合物
  final dynamic ssxw; // 膳食纤维
  final dynamic gai; // 钙
  final dynamic tei; // 铁
  final dynamic xin; // 锌
  final dynamic la; // 钠
  final dynamic jia; // 钾
  final dynamic ling; // 磷
  final dynamic mei; // 镁
  final dynamic xi; // 硒
  final dynamic wssa; // 维生素A
  final dynamic wsfc; // 维生素C
  final dynamic wsse; // 维生素E
  final dynamic las; // 硫胺素
  final dynamic su; // 核黄素
  final dynamic ys; // 烟酸
  final dynamic dgc; // 胆固醇

  // 确保所有final字段都被初始化
  Nutrition({
    required this.name,
    required this.type,
    this.rl,
    this.dbz,
    this.zf,
    this.shhf,
    this.ssxw,
    this.gai,
    this.tei,
    this.xin,
    this.la,
    this.jia,
    this.ling,
    this.mei,
    this.xi,
    this.wssa,
    this.wsfc,
    this.wsse,
    this.las,
    this.su,
    this.ys,
    this.dgc,
  });

  factory Nutrition.fromJson(Map<String, dynamic> json) {
    return Nutrition(
      name: json['name'] ?? '',
      type: json['type'] ?? '',
      rl: json['rl'],
      dbz: json['dbz'],
      zf: json['zf'],
      shhf: json['shhf'],
      ssxw: json['ssxw'],
      gai: json['gai'],
      tei: json['tei'],
      xin: json['xin'],
      la: json['la'],
      jia: json['jia'],
      ling: json['ling'],
      mei: json['mei'],
      xi: json['xi'],
      wssa: json['wssa'],
      wsfc: json['wsfc'],
      wsse: json['wsse'],
      las: json['las'],
      su: json['su'],
      ys: json['ys'],
      dgc: json['dgc'],
    );
  }
}

class NutritionResponse {
  final List<Nutrition> items;

  NutritionResponse({required this.items});

  factory NutritionResponse.fromJson(Map<String, dynamic> json) {
    // API返回格式可能是list或直接包含数据
    if (json['result'] is List) {
      return NutritionResponse(
        items: List<Nutrition>.from(
            json['result'].map((item) => Nutrition.fromJson(item))),
      );
    } else if (json['result']['list'] != null) {
      // 处理当结果在list字段中的情况
      final List<dynamic> list = json['result']['list'];
      return NutritionResponse(
        items:
            List<Nutrition>.from(list.map((item) => Nutrition.fromJson(item))),
      );
    } else {
      // 如果result直接包含数据（单个item）
      return NutritionResponse(
        items: [Nutrition.fromJson(json['result'])],
      );
    }
  }
}
